package com.morgan.basemodule.global

import android.content.Context
import android.util.SparseArray
import com.morgan.basemodule.app.CommonApp

/**
 *description：全局数据管理
 *<br>author：caowugao
 *<br>time：2021/4/2 0002 16:22
 */
class GlobalDataManager private constructor(){

    private val caches : SparseArray<Any> by lazy { SparseArray() }

    class Holder private constructor(){
        companion object {
            val INSTANCE = GlobalDataManager()
        }
    }

    companion object {
        fun getInstance() = Holder.INSTANCE
    }

    fun getContext() : Context = CommonApp.app

    fun size() : Int {
        synchronized(caches) {
            return caches.size()
        }
    }

    fun <T> put(key : Int, data : T?, maxSize : Int = -1) {
        if (maxSize > 0 && size() > 0) {
            synchronized(caches) {
                val size = caches.size()
                val removeSize = if (size < maxSize) maxSize - size else -1
                for (i in 0 until removeSize) {
                    caches.removeAt(0)
                }
            }
        }
        synchronized(caches) {
            caches.put(key, data)
        }
    }

    fun <T> get(key : Int) : T? {
        synchronized(caches) {
            return caches.get(key) as? T
        }
    }

    fun removeByKey(key : Int) {
        synchronized(caches) {
            caches.remove(key)
        }
    }

    fun removeByIndex(index : Int) {
        synchronized(caches) {
            try {
                caches.removeAt(index)
            } catch (e : Throwable) {
                e.printStackTrace()
            }
        }
    }

    fun clear() {
        synchronized(caches) {
            caches.clear()
        }
    }

}